package socket.webSocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class WebSocketServer {
  public static void main(String[] args) throws InterruptedException {
    // 1. 创建 boos/ worker group
    NioEventLoopGroup boosGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    
    // 2. 创建 server bootstrap
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap
        .group(boosGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline pipeline = socketChannel.pipeline();
            
            // 添加 一些别的处理器
            pipeline.addLast(
                new HttpServerCodec(),
                new HttpObjectAggregator(65536),
                new WebSocketServerProtocolHandler("/websocket"),
                new WebSocketServerHandler()
            );
          }
        })
        .option(ChannelOption.SO_BACKLOG, 128)
        .childOption(ChannelOption.SO_KEEPALIVE, true);
    
    ChannelFuture channelFuture = serverBootstrap.bind(8111).sync();
    
    // 等待 socket connect close
    channelFuture.channel().closeFuture().sync();
  }
}


class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channel active");
  }
  
  @Override
  public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channel unregistered");
  }
  
  @Override
  public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channel registered");
  }
  
  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channel inactive");
  }
  
  @Override
  protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame frame) throws Exception {
    // 拿到 客户端
    Channel client = channelHandlerContext.channel();
    
    // 针对文本类型的处理
    if (frame instanceof TextWebSocketFrame) {
      String text = ((TextWebSocketFrame) frame).text();
      System.out.println("Received message: " + text);
      
      // 针对 客户端进行回复
      client.writeAndFlush(new TextWebSocketFrame("server received: " + text + " -- server"));
    } else {
      System.out.println("这是 其他类型的处理 ...");
    }
  }
}
